package week11;

import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestExecutor {
	public static void main(String[] args) {
		
		//1.Executor演示
		Runnable task1 = new SimpleTask();
		Runnable task2 = new SimpleTask();
		Executor executor = new Executor() {
			
			@Override
			public void execute(Runnable command) {
				command.run();
			}
		};
		System.out.println("1.直接执行传入的runnable对象的run方法");
		executor.execute(task1);
		executor.execute(task2);
		/***********************************************************/
		Executor executor2 = new Executor() {
			
			@Override
			public void execute(Runnable command) {
				new Thread(command).start();
			}
		};
		System.out.println("2.对传入的runnable对象，建立线程并运行");
		executor2.execute(task1);
		executor2.execute(task2);
		
		//2.ExecutorService演示
		ExecutorService executorService = Executors.newCachedThreadPool();
		//ExecutorService executorService1 = Executors.newFixedThreadPool(2);//指定在池中建立固定数量线程
		//ExecutorService executorService2= Executors.newSingleThreadExecutor();//使用单个线程执行排定的工作
		System.out.println("3.必要时建立线程，传入的runnable对象可能在新建的线程中执行，也可能重复利用现有的线程");
		executorService.execute(task1);
		executorService.execute(task2);
		executorService.shutdown();//在所有传入的runnable对象都完成后，关闭
		
		
		//3.ScheduledExecutorService演示
		System.out.println("4.按照指定间隔执行任务ScheduledTask");
		Runnable scheduledTask = new Runnable() {
			
			@Override
			public void run() {
				System.out.println(LocalDateTime.now());
				
			}
		};
		ScheduledExecutorService scheduledService = Executors.newSingleThreadScheduledExecutor();
		//ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(2);
		//第一次执行前先延迟1s，后面每次执行的间隔为2s
		scheduledService.scheduleWithFixedDelay(scheduledTask, 1000, 2000, TimeUnit.MILLISECONDS);
		
	}
}

class SimpleTask implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 6; i++) {
			try {
				System.out.println(Thread.currentThread().getName()+" "+i);
				TimeUnit.MILLISECONDS.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
